<template>
  <div class="map-container">
    <div id="map" class="map"></div>
    <div id="coordinates" class="coordinates"></div>
    <!-- 弹窗容器 -->
    <div id="popup" class="ol-popup">
      <!-- <a href="#" id="popup-closer" class="ol-popup-closer"></a> -->
      <div id="popup-content"></div>
    </div>
  </div>
</template>

<script>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import { Vector as VectorLayer, Tile as TileLayer } from 'ol/layer';
import { Vector as VectorSource, XYZ } from 'ol/source';
import { Style, Circle, Fill, Stroke, Icon, Text } from 'ol/style';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import { fromLonLat, transform } from 'ol/proj';
import Overlay from 'ol/Overlay';

export default {
  name: 'PointTypes',
  data() {
    return {
      map: null,
      vectorSource: null,
      pulseSource: null,
      labelSource: null,
      popup: null,
      points: [
        {
          type: 'scenic',
          name: '天安门',
          coordinates: [116.397428, 39.90923],
          icon: '/images/markers/PP_CJ.png',
          pulse: true,
          size: [20, 20],
          popupContent: {
            title: '天安门',
            content: `
              <div class="popup-content">
                <div class="popup-info">
                  <p>天安门坐落在中国北京市中心,是中华人民共和国的象征。</p>
                  <p>地址：北京市东城区长安街</p>
                </div>
                <div class="popup-stats">
                  <div class="stat-item">
                    <label>建成年份</label>
                    <span>1420年</span>
                  </div>
                  <div class="stat-item">
                    <label>占地面积</label>
                    <span>4800平方米</span>
                  </div>
                </div>
              </div>
            `
          }
        },
        {
          type: 'hospital',
          name: '协和医院',
          coordinates: [116.417795, 39.913828],
          icon: '/images/markers/cjyl.gif',
          pulse: true,
          size: [20, 20],
          popupContent: {
            title: '北京协和医院',
            content: `
              <div class="popup-content">
                <div class="popup-info">
                  <p>北京协和医院是中国最著名的医院之一，始建于1921年。</p>
                  <p>地址：北京市东城区帅府园一号</p>
                </div>
                <div class="popup-stats">
                  <div class="stat-item">
                    <label>医院等级</label>
                    <span>三级甲等</span>
                  </div>
                  <div class="stat-item">
                    <label>床位数</label>
                    <span>2000+</span>
                  </div>
                </div>
              </div>
            `
          }
        }
      ]
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      // 创建弹窗 Overlay
      this.popup = new Overlay({
        element: document.getElementById('popup'),
        positioning: 'bottom-center',
        stopEvent: false,
        offset: [0, -10]
      });

      // 创建地图
      this.map = new Map({
        target: 'map',
        layers: [
          new TileLayer({
            source: new XYZ({
              url: 'https://webst0{1-4}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
              crossOrigin: 'anonymous'
            }),
            zIndex: 0
          }),
        ],
        view: new View({
          center: fromLonLat([116.397428, 39.90923]),
          zoom: 12
        }),
        overlays: [this.popup]
      });

      // 添加初始点位到默认图层
      this.addPoint(this.points[0], {
        layerId: 'labelLayer'
      });
      this.addPoint(this.points[1], {
        layerId: 'labelLayer1q',
        layerOptions: {
          style: new Style({
            image: new Icon({
              src: '/images/markers/cjyl.gif',
              scale: 2,  // 使用 scale 控制图标大小
              anchor: [0.5, 0.5],
              anchorXUnits: 'fraction',
              anchorYUnits: 'fraction'
            })
          }),
          zIndex: 2
        }
      });

      // 添加事件监听
      this.addMapListeners();

      // 启动动画
      this.animate();
    },

    // 创建点样式
    createPointStyle(feature) {
      const style = new Style({
        text: new Text({
          text: feature.get('name'),
          font: '12px sans-serif',
          offsetY: 25,
          textAlign: 'center',
          textBaseline: 'middle',
          fill: new Fill({ color: '#333' }),
          stroke: new Stroke({ color: '#fff', width: 3 })
        })
      });

      if (!feature.get('isGif')) {
        style.setImage(new Icon({
          src: feature.get('icon'),
          scale: 0.8,
          anchor: [0.5, 0.5],
          anchorXUnits: 'fraction',
          anchorYUnits: 'fraction'
        }));
      }

      return style;
    },

    // 创建闪烁效果样式
    createPulseStyle(feature) {
      if (!feature.get('pulse')) return null;

      const startTime = feature.get('pulseStartTime');
      const currentTime = Date.now();
      const elapsedTime = currentTime - startTime;

      if (elapsedTime <= 3000) {
        const phase = (currentTime % 1500) / 1500;
        const radius = 15 + (35 * phase);
        const opacity = 0.8 - phase;

        return new Style({
          image: new Circle({
            radius: radius,
            fill: new Fill({
              color: `rgba(255, 0, 0, ${opacity * 0.3})`
            }),
            stroke: new Stroke({
              color: `rgba(255, 0, 0, ${opacity})`,
              width: 2
            })
          })
        });
      }

      feature.set('pulse', false);
      return null;
    },

    // 添加点位方法
    addPoint(pointData, options = {}) {
      // 通过图标后缀判断是否为 GIF
      const isGif = pointData.icon?.toLowerCase().endsWith('.gif');
      
      const {
        layerId,
        layerOptions = {}
      } = options;

      // 如果需要闪烁效果，添加时间戳
      if (pointData.pulse) {
        pointData.pulseStartTime = Date.now();
      }

      const feature = new Feature({
        geometry: new Point(fromLonLat(pointData.coordinates)),
        isGif,  // 添加 isGif 属性
        ...pointData
      });

      // 查找现有图层
      let targetLayer = null;
      if (layerId) {
        targetLayer = this.map.getLayers().getArray().find(layer => layer.get('id') === layerId);
      }
      if (targetLayer) {
        console.log("featurefeaturefeature", feature);
        // 使用现有图层
        targetLayer.getSource().addFeature(feature);

        // 如果需要闪烁效果，添加到闪烁图层
        if (pointData.pulse) {
          const pulseLayerId = `${layerId}_pulse`;
          let pulseLayer = this.map.getLayers().getArray().find(layer => layer.get('id') === pulseLayerId);

          if (!pulseLayer) {
            // 如果闪烁图层不存在，创建新的闪烁图层
            const pulseSource = new VectorSource();
            pulseLayer = new VectorLayer({
              id: pulseLayerId,
              source: pulseSource,
              style: this.createPulseStyle,
              zIndex: targetLayer.getZIndex() - 1  // 确保在标注图层下方
            });
            this.map.addLayer(pulseLayer);
          }

          pulseLayer.getSource().addFeature(feature);
        }
      } else {
        // 创建新的图层
        const newSource = new VectorSource();
        const newLayer = new VectorLayer({
          id: layerId || `layer_${Date.now()}`,  // 如果没有提供 ID，生成一个唯一 ID
          source: newSource,
          style: layerOptions.style || this.createPointStyle,
          zIndex: layerOptions.zIndex || 3,
          ...layerOptions
        });

        newSource.addFeature(feature);
        this.map.addLayer(newLayer);

        // 如果需要闪烁效果，创建对应的闪烁图层
        if (pointData.pulse) {
          const pulseSource = new VectorSource();
          const pulseLayer = new VectorLayer({
            id: `${newLayer.get('id')}_pulse`,
            source: pulseSource,
            style: this.createPulseStyle,
            zIndex: (layerOptions.zIndex || 3) - 1
          });

          pulseSource.addFeature(feature);
          this.map.addLayer(pulseLayer);
        }
      }

      // 如果是GIF标记，创建Overlay
      if (isGif) {
        this.addGifOverlay(pointData);
      }

      return feature;
    },

    // 添加GIF标记
    addGifOverlay(point) {
      const gifElement = document.createElement('div');
      gifElement.className = 'gif-marker';
      gifElement.style.backgroundImage = `url(${point.icon})`;

      if (point.size) {
        gifElement.style.width = `${point.size[0]}px`;
        gifElement.style.height = `${point.size[1]}px`;
        gifElement.style.backgroundSize = '100% 100%';
      }

      // 添加悬停事件
      gifElement.addEventListener('mouseenter', (e) => {
        e.stopPropagation();
        const popupContent = point.popupContent || {};
        const content = `
          <h3 class="popup-title">${popupContent.title || point.name}</h3>
          ${popupContent.content || ''}
        `;

        document.getElementById('popup-content').innerHTML = content;
        this.popup.setPosition(fromLonLat(point.coordinates));
      });

      // 添加鼠标离开事件
      gifElement.addEventListener('mouseleave', (e) => {
        e.stopPropagation();
        this.popup.setPosition(undefined);
      });

      const gifOverlay = new Overlay({
        element: gifElement,
        position: fromLonLat(point.coordinates),
        positioning: 'center-center',
        offset: [0, 0],
        stopEvent: true  // 阻止事件传递到地图，避免与地图事件冲突
      });

      this.map.addOverlay(gifOverlay);
    },

    // 修改地图事件监听
    addMapListeners() {
      // 显示坐标
      this.map.on('pointermove', (evt) => {
        const coords = transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
        document.getElementById('coordinates').innerHTML =
          `经度: ${coords[0].toFixed(6)}, 纬度: ${coords[1].toFixed(6)}`;
      });

      // 修改鼠标样式和弹窗处理
      this.map.on('pointermove', (e) => {
        const pixel = this.map.getEventPixel(e.originalEvent);
        const feature = this.map.forEachFeatureAtPixel(pixel, feature => feature);
        
        // 更新鼠标样式
        this.map.getViewport().style.cursor = feature ? 'pointer' : '';
        
        // 处理非 GIF 点位的悬停弹窗
        if (feature && !feature.get('isGif')) {
          const coordinates = feature.getGeometry().getCoordinates();
          const popupContent = feature.get('popupContent') || {};
          const content = `
            <h3 class="popup-title">${popupContent.title || feature.get('name')}</h3>
            ${popupContent.content || ''}
          `;
          
          document.getElementById('popup-content').innerHTML = content;
          this.popup.setPosition(coordinates);
        } else if (!e.originalEvent.target.closest('.gif-marker')) {
          // 如果鼠标不在 GIF 标记上，则关闭弹窗
          this.popup.setPosition(undefined);
        }
      });
    },

    // 动画循环
    animate() {
      // 获取所有闪烁图层
      const pulseLayers = this.map.getLayers().getArray().filter(layer =>
        layer.get('id') && layer.get('id').endsWith('_pulse')
      );

      // 检查是否有活跃的闪烁效果
      const hasActivePulse = pulseLayers.some(layer => {
        const features = layer.getSource().getFeatures();
        return features.some(feature =>
          feature.get('pulse') &&
          (Date.now() - feature.get('pulseStartTime') <= 3000)
        );
      });

      if (hasActivePulse) {
        // 触发所有闪烁图层重绘
        pulseLayers.forEach(layer => layer.changed());
        this.map.render();
        requestAnimationFrame(this.animate.bind(this));
      }
    }
  }
};
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.coordinates {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1000;
}

.gif-marker {
  width: 32px;
  height: 32px;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center center;
  pointer-events: none;
}

/* 弹窗样式 */
.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 280px;
  max-width: 400px;
  font-size: 13px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
  font-size: 16px;
  color: #666;
}

.ol-popup-closer:after {
  content: "✖";
}

:deep(.popup-title) {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

:deep(.popup-info) {
  font-size: 13px;
  color: #606266;
}

:deep(.popup-content) {
  font-size: 13px;
}


:deep(.popup-info p) {
  margin: 5px 0;
  color: #666;
}

:deep(.popup-stats) {
  display: flex;
  justify-content: space-between;
  border-top: 1px dashed #eee;
  padding-top: 10px;
}

:deep(.stat-item) {
  text-align: center;
  flex: 1;
}

:deep(.stat-item label) {
  display: block;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

:deep(.stat-item span) {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
</style> 